<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <!-- 消费统计模块 -->
    <el-card class="mb-20px" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>消费统计（近一年）</span>
        </div>
      </template>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="用户总消费">
          <span class="text-red-500 font-bold text-20px">{{ formatAmount(userConsumptionStats.totalAmount) }}</span>
        </el-descriptions-item>
      </el-descriptions>

      <div class="mt-20px">
        <div class="text-16px font-bold mb-10px">各宠物消费情况：</div>
        <el-table :data="userConsumptionStats.petStats" style="width: 100%">
          <el-table-column prop="petName" label="宠物名称" />
          <el-table-column prop="amount" label="消费金额">
            <template #default="scope">
              <span class="text-red-500">{{ formatAmount(scope.row.amount) }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 宠物列表模块 -->
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>宠物列表</span>
        </div>
      </template>
      <el-table
        v-loading="loading"
        :data="petList"
        :stripe="true"
        :show-overflow-tooltip="true"
      >
        <el-table-column label="宠物名称" align="center" prop="petName" />
        <el-table-column label="宠物头像" align="center" prop="avatarUrl">
          <template #default="scope">
            <el-image
              style="width: 60px; height: 60px"
              :src="scope.row.avatarUrl"
              :preview-src-list="[scope.row.avatarUrl]"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="120px">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="openPetConsumptionDialog(scope.row)"
            >
              为它消费
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <template #footer>
      <el-button @click="dialogVisible = false">关 闭</el-button>
    </template>
  </Dialog>

  <!-- 宠物消费弹窗 -->
  <PetConsumptionDialog ref="petConsumptionDialogRef" @success="handleConsumptionSuccess" />
</template>

<script setup lang="ts">
import {Pet, PetApi} from '@/api/javainfo/pet'
import {FinancialFlowApi, UserConsumptionStats} from '@/api/javainfo/financialflow'
import PetConsumptionDialog from './PetConsumptionDialog.vue'

/** 用户消费 弹窗 */
defineOptions({ name: 'UserConsumptionDialog' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('用户消费') // 弹窗的标题
const loading = ref(false) // 表格的加载中
const petList = ref<Pet[]>([]) // 宠物列表数据
const userId = ref<number>() // 用户ID

// 用户消费统计数据
const userConsumptionStats = ref<UserConsumptionStats>({
  userId: 0,
  totalAmount: 0,
  petStats: []
})

/** 格式化金额（分转元） */
const formatAmount = (amount: number) => {
  if (amount === undefined || amount === null) return '¥0.00'
  return '¥' + (amount / 100).toFixed(2)
}

/** 打开弹窗 */
const open = async (id: number) => {
  dialogVisible.value = true
  userId.value = id
  await Promise.all([
    getPetList(),
    getUserConsumptionStats()
  ])
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 获取用户关联的宠物列表 */
const getPetList = async () => {
  loading.value = true
  try {
    // 调用宠物API，根据用户ID查询关联的宠物
    const params = {
      ownerUserId: userId.value
    }
    const data = await PetApi.getPetPage(params)
    petList.value = data.list || []
  } finally {
    loading.value = false
  }
}

/** 获取用户消费统计数据 */
const getUserConsumptionStats = async () => {
  try {
    const data = await FinancialFlowApi.getUserConsumptionStats(userId.value!)
    userConsumptionStats.value = data || {
      userId: userId.value!,
      totalAmount: 0,
      petStats: []
    }
  } catch (error) {
    console.error('获取用户消费统计数据失败', error)
    userConsumptionStats.value = {
      userId: userId.value!,
      totalAmount: 0,
      petStats: []
    }
  }
}

/** 打开宠物消费弹窗 */
const petConsumptionDialogRef = ref()
const openPetConsumptionDialog = (pet: Pet) => {
  petConsumptionDialogRef.value.open(userId.value!, pet)
}

/** 处理消费成功回调 */
const handleConsumptionSuccess = () => {
  // 重新加载数据
  Promise.all([
    getPetList(),
    getUserConsumptionStats()
  ])
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.text-red-500 {
  color: #f56c6c;
}

.font-bold {
  font-weight: bold;
}

.text-20px {
  font-size: 20px;
}

.text-16px {
  font-size: 16px;
}

.mb-10px {
  margin-bottom: 10px;
}

.mt-20px {
  margin-top: 20px;
}
</style>

